package com.ganlucode.springcloud.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author GanLu
 * @date 2020-08-11 19:46
 */
@Slf4j
@RestController
@RequestMapping("/eureka")
public class EurekaController {

    @Autowired
    private LoadBalancerClient client;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Value("${spring.application.name}")
    private String applicationName;

    public static final String SERVICE_NAME_A = "SERVICE-A";

    @GetMapping("/sayHi")
    public String sayHi() {

        return "Hello, this is "+applicationName;
    }

    @GetMapping("/a/hello")
    public String hello() {
        ServiceInstance instance = client.choose(SERVICE_NAME_A);

        if (instance == null) {
            return "No available instances";
        }

        String target = String.format("http://%s:%s/eureka/sayHi",
                instance.getHost(),
                instance.getPort());
        log.info("url is {}", target);

        return restTemplate.getForObject(target, String.class);
    }

    @GetMapping("/a/hello2")
    public String hello2() {
        List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(SERVICE_NAME_A);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < serviceInstanceList.size(); i++) {
            ServiceInstance serviceInstance = serviceInstanceList.get(i);
            String target = String.format("http://%s:%s/eureka/sayHi",
                    serviceInstance.getHost(),
                    serviceInstance.getPort());
            log.info("url is {}", target);
            sb.append(restTemplate.getForObject(target, String.class));
            sb.append("\n");
        }
        return sb.toString();
    }


}
